import { IPC_CHANNELS } from 'shared/ipcChannels'
import type { ScopedLogger } from '#/logger'
import type { IPerformPopup } from '#/platforms/IPlatform'
import {
  errorMessage,
  mergeWithoutArray,
  randomInt,
  takeScreenshot,
} from '#/utils'
import windowManager from '#/windowManager'
import { createIntervalTask } from './IntervalTask'
import { runWithRetry } from './retry'

const TASK_NAME = '自动弹窗'

const retryOptions = {
  maxRetries: 3,
  retryDelay: 1000,
}

export function createAutoPopupTask(
  platform: IPerformPopup,
  taskConfig: AutoPopupConfig,
  account: Account,
  _logger: ScopedLogger,
) {
  const logger = _logger.scope(TASK_NAME)
  let arrayIndex = -1
  let config = { ...taskConfig }
  const skippedGoods = new Set<number>() // 记录跳过的商品，避免死循环

  async function execute(signal: AbortSignal) {
    // 如果所有商品都跳过了，清空跳过记录重新开始
    if (skippedGoods.size >= config.goodsIds.length) {
      logger.warn('所有商品都已尝试过，清空跳过记录重新开始')
      skippedGoods.clear()
    }

    let attempts = 0
    const maxAttempts = config.goodsIds.length // 最多尝试所有商品

    while (attempts < maxAttempts) {
      if (signal.aborted) {
        return
      }

      const goodsId = getNextGoodsId()
      attempts++

      // 如果这个商品之前跳过了，换下一个
      if (skippedGoods.has(goodsId)) {
        logger.debug(`商品 ${goodsId} 之前已跳过，换下一个`)
        continue
      }

      try {
        await runWithRetry(
          async () => {
            if (signal.aborted) {
              return
            }
            await platform.performPopup(goodsId)
            logger.success(`商品 ${goodsId} 讲解成功`)
          },
          {
            ...retryOptions,
            logger,
            onRetryError: () =>
              takeScreenshot(platform.getPopupPage(), TASK_NAME, account.name),
          },
        )
        // 成功后返回
        return
      } catch (err) {
        const errMsg = errorMessage(err)
        
        // 判断是否是找不到商品的错误
        if (errMsg.includes('仍未找到商品') || errMsg.includes('找不到')) {
          logger.warn(`商品 ${goodsId} 未找到，自动跳过换下一个商品`)
          skippedGoods.add(goodsId) // 记录跳过的商品
          // 继续循环尝试下一个商品
          continue
        }
        
        // 其他类型的错误，停止任务
        logger.error(`商品 ${goodsId} 执行失败: ${errMsg}`)
        windowManager.send(IPC_CHANNELS.tasks.autoPopUp.stoppedEvent, account.id)
        throw err
      }
    }

    // 所有商品都尝试过了还是失败
    logger.error('所有商品都无法找到或执行失败')
    windowManager.send(IPC_CHANNELS.tasks.autoPopUp.stoppedEvent, account.id)
    throw new Error('所有商品都无法找到或执行失败，请检查商品配置')
  }

  function getNextGoodsId(): number {
    if (config.random) {
      arrayIndex = randomInt(0, config.goodsIds.length - 1)
    } else {
      arrayIndex = (arrayIndex + 1) % config.goodsIds.length
    }
    return config.goodsIds[arrayIndex]
  }

  function updateConfig(newConfig: Partial<AutoPopupConfig>) {
    try {
      const mergedConfig = mergeWithoutArray(config, newConfig)
      validateConfig(mergedConfig)
      if (newConfig.scheduler?.interval)
        intervalTask.updateInterval(config.scheduler.interval)
      config = mergedConfig
      // 更新配置后清空跳过记录，重新开始
      skippedGoods.clear()
      logger.info('配置已更新，清空跳过记录')
      // 更新配置后重新启动任务
      intervalTask.restart()
    } catch (error) {
      logger.error(`配置更新失败: ${errorMessage(error)}`)
      throw error
    }
  }

  function validateConfig(userConfig: AutoPopupConfig) {
    intervalTask.validateInterval(userConfig.scheduler.interval)
    if (userConfig.goodsIds.length === 0)
      throw new Error('商品配置验证失败: 必须提供至少一个商品ID')

    logger.info(`商品配置验证通过，共加载 ${userConfig.goodsIds.length} 个商品`)
  }

  const intervalTask = createIntervalTask(execute, {
    interval: config.scheduler.interval,
    taskName: TASK_NAME,
    logger,
  })

  return {
    ...intervalTask,
    updateConfig,
  }
}
